import { createStore } from 'vuex'

export default createStore({
  state: {
    // 底图信息
    backgroundImage: {
      url: '',
      width: 0,
      height: 0
    },
    // 标注点数组
    annotations: [],
    // 当前编辑的标注点ID
    currentEditingId: null
  },
  getters: {
    getAnnotationById: (state) => (id) => {
      return state.annotations.find(annotation => annotation.id === id)
    },
    hasBackgroundImage: (state) => {
      return !!state.backgroundImage.url
    }
  },
  mutations: {
    // 设置底图
    SET_BACKGROUND_IMAGE(state, imageData) {
      state.backgroundImage = imageData
    },
    // 添加标注点
    ADD_ANNOTATION(state, annotation) {
      state.annotations.push({
        id: Date.now() + Math.random(),
        title: annotation.title || '新标注点',
        description: annotation.description || '',
        left: annotation.left,
        top: annotation.top,
        ...annotation
      })
    },
    // 更新标注点
    UPDATE_ANNOTATION(state, { id, data }) {
      const index = state.annotations.findIndex(item => item.id === id)
      if (index !== -1) {
        state.annotations[index] = { ...state.annotations[index], ...data }
      }
    },
    // 删除标注点
    DELETE_ANNOTATION(state, id) {
      const index = state.annotations.findIndex(item => item.id === id)
      if (index !== -1) {
        state.annotations.splice(index, 1)
      }
    },
    // 设置当前编辑的标注点
    SET_CURRENT_EDITING(state, id) {
      state.currentEditingId = id
    },
    // 清空所有数据
    CLEAR_ALL_DATA(state) {
      state.backgroundImage = { url: '', width: 0, height: 0 }
      state.annotations = []
      state.currentEditingId = null
    }
  },
  actions: {
    // 保存标注数据到localStorage
    saveToLocal({ state }) {
      const data = {
        backgroundImage: state.backgroundImage,
        annotations: state.annotations
      }
      localStorage.setItem('annotation-data', JSON.stringify(data))
    },
    // 从localStorage加载数据
    loadFromLocal({ commit }) {
      const data = localStorage.getItem('annotation-data')
      if (data) {
        try {
          const parsed = JSON.parse(data)
          if (parsed.backgroundImage) {
            commit('SET_BACKGROUND_IMAGE', parsed.backgroundImage)
          }
          if (parsed.annotations) {
            parsed.annotations.forEach(annotation => {
              commit('ADD_ANNOTATION', annotation)
            })
          }
        } catch (error) {
          console.error('加载本地数据失败:', error)
        }
      }
    }
  },
  modules: {
  }
})
